package com.mgface.foundation.framework;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.system.ApplicationPidFileWriter;
import org.springframework.boot.actuate.system.EmbeddedServerPortFileWriter;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.ContextRefreshedEvent;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@SpringBootApplication
public class Application implements CommandLineRunner {

    private final static Logger log = LogManager.getLogger(Application.class);

    private static void appListener(ApplicationEvent e) {
        LocalDateTime datetime = LocalDateTime.now();
        String currentTime = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.info("触发事件:" + e.getClass().getSimpleName());
        if (e instanceof ApplicationPreparedEvent) {
            log.info("在refresh开始之前,但在bean定义已加载之后触发{ApplicationPreparedEvent}事件,时间为{}",currentTime);
        }
        if (e instanceof ContextRefreshedEvent) {
            log.info("spring上下文被刷新,时间为{}", currentTime);
        }
        if (e instanceof ApplicationReadyEvent) {
            log.info("应用就绪事件,时间为{}", currentTime);
        }
        if (e instanceof EmbeddedServletContainerInitializedEvent) {
            log.info("嵌入式Servlet容器初始化完成,时间为{}", currentTime);
        }
        if (e instanceof ApplicationFailedEvent) {
            log.info("应用启动异常,时间为{},事件为{}", LocalDateTime.now(), "error");
        }
    }

    @Override
    public void run(String... args) throws Exception {
        log.info(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 {} <<<<<<<<<<<<<", Application.class.getSimpleName());
    }

    public static void main(String[] args) {
        SpringApplication boot = new SpringApplication(Application.class);
        //boot.setShowBanner(true);
        //创建进程监控的文件
        boot.addListeners(Application::appListener, new EmbeddedServerPortFileWriter(),new ApplicationPidFileWriter());
        // 设置正确类型的ApplicationContext,这里为web项目的applicationContext
        boot.setWebEnvironment(true);
        boot.setApplicationContextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
        boot.setRegisterShutdownHook(true);
        // 禁用命令行配置
        boot.setAddCommandLineProperties(false);
        boot.run(args);
    }


}
